﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace OA.Service
{
    /// <summary>
    /// WebService 的摘要说明
    /// </summary>
    public class Index : IHttpHandler
    {
        HttpResponse Response = null;
        HttpRequest Request = null;
        System.Web.SessionState.HttpSessionState Session = null;
        HttpServerUtility Server = null;
        HttpApplicationState Application = null;

        public void ProcessRequest(HttpContext context)
        {
            Response = context.Response;
            Request = context.Request;
            Session = context.Session;
            Server = context.Server;
            Application = context.Application;
            Response.ContentType = "text/xml";
            string xml = null;
            if (!string.IsNullOrEmpty(Request.QueryString["xml"]))
            {
                xml = Request.QueryString["xml"];
            }
            else
            {
                byte[] byts = new byte[Request.InputStream.Length];
                Request.InputStream.Read(byts, 0, byts.Length);
                xml = System.Text.Encoding.Default.GetString(byts);
            }
            var result=Common.SerializationHelper.Serialize(MethodProcess(xml));
            Response.Write(result);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public Model.BaseResponse MethodProcess(string xml)
        {
            Model.BaseResponse ret = new Model.BaseResponse();
            try
            {
                if (string.IsNullOrEmpty(xml))
                {
                    ret.Code = 10;
                    ret.Message = "传入的参数不能为空";
                    return ret;
                }
                var req = Common.SerializationHelper.DeSerialize<Model.BaseReqeust<Model.BaseResponse>>(xml);
                var loginret=new BLL.Manager().ValidateUserByMd5(req.Head.UserName,req.Head.PassWord);
                if (loginret.success == false)
                {
                    ret.Code = 15;
                    ret.Message = "调用WebService失败，" + loginret.message;
                    return ret;
                }
                if (string.IsNullOrEmpty(req.Head.ActionName))
                {
                    ret.Code = 20;
                    ret.Message = "Head>ActionName不能为空";
                    return ret;
                }
                var auth=new BLL.Authority();
                if (auth.ValidateAuthority(Common.EnumType.ResourceType.WebSite, Common.Keys.WebSiteCode, null, null, req.Head.UserName).success == false)
                {
                    ret.Code = 25;
                    ret.Message = "没有调用该服务站点的权限";
                    return ret;
                }
                if (auth.ValidateAuthority(Common.EnumType.ResourceType.Menu, Common.Keys.WebSiteCode,req.Head.ActionName, null, req.Head.UserName).success == false)
                {
                    ret.Code = 25;
                    ret.Message = "没有调用该方法的权限";
                    return ret;
                }
                var method = this.GetType().GetMethod(req.Head.ActionName, new Type[] { typeof(string) });
                if (method==null)
                {
                    ret.Code = 30;
                    ret.Message = req.Head.ActionName + "方法不存在";
                    return ret;
                }
                ret = method.Invoke(this, new object[] { xml }) as Model.BaseResponse;
            }
            catch (Exception e)
            {
                ret.Code = 90;
                ret.Message = e.Message;
            }
            return ret;
        }

        /// <summary>
        /// 登陆验证
        /// </summary>
        public Model.LoginResponse LoginValidate(string xml)
        {
            Model.LoginResponse ret = new Model.LoginResponse();
            var req = Common.SerializationHelper.DeSerialize<Model.LoginValidateRequest>(xml);
            var loginret = new BLL.Manager().ValidateUserByMd5(req.UserName, req.PassWord);
            ret.Code = loginret.count;
            ret.Message = loginret.message;
            if (loginret.success)
            {
                ret.Code = 0;
                var loginUser = loginret.data as Model.Data.User;
                ret.User = new Model.Data.User()
                {
                    UserName = loginUser.UserName,
                    Password = loginUser.Password,
                    RealName = loginUser.RealName,
                    GroupID = loginUser.GroupID,
                    Email = loginUser.Email,
                    Telephone = loginUser.Telephone,
                    CreatTime = loginUser.CreatTime
                };
            }
            return ret;
        }

        #region 权限验证
        /// <summary>
        /// 验证站点权限
        /// </summary>
        public Model.BaseResponse ValidateWebSiteAuthority(string xml)
        {
            var req = Common.SerializationHelper.DeSerialize<Model.ValidateWebSiteAuthorityRequest>(xml);
            return ValidateAuthority(Common.EnumType.ResourceType.WebSite, req.UserName, req.WebSiteCode, null, null);
        }

        /// <summary>
        /// 验证菜单权限
        /// </summary>
        public Model.BaseResponse ValidateMenuAuthority(string xml)
        {
            var req = Common.SerializationHelper.DeSerialize<Model.ValidateMenuAuthorityRequest>(xml);
            return ValidateAuthority(Common.EnumType.ResourceType.Menu, req.UserName, req.WebSiteCode, req.MenuCode, null);
        }

        /// <summary>
        /// 验证按钮权限
        /// </summary>
        public Model.BaseResponse ValidateButtonAuthority(string xml)
        {
            var req = Common.SerializationHelper.DeSerialize<Model.ValidateButtonAuthorityRequest>(xml);
            return ValidateAuthority(Common.EnumType.ResourceType.Button, req.UserName, req.WebSiteCode, req.MenuCode, req.WebSiteCode);
        }
       
        /// <summary>
        /// 验证用户权限
        /// </summary>
        private Model.BaseResponse ValidateAuthority(Common.EnumType.ResourceType type, string UserName, string WebSiteCode, string MenuCode, string ButtonCode)
        {
            Model.BaseResponse ret = new Model.BaseResponse();
            var cret = new BLL.Authority().ValidateAuthority(type, WebSiteCode, MenuCode, ButtonCode, UserName);
            ret.Message = cret.message;
            ret.Code = cret.success ? 0 : 1;
            return ret;
        }
        #endregion

        #region 获取用户资源列表
        /// <summary>
        /// 获取用户拥有权限的站点
        /// </summary>
        public Model.GetUserWebSiteResponse GetUserWebSite(string xml)
        {
            var req = Common.SerializationHelper.DeSerialize<Model.GetUserWebSiteReqeust>(xml);
            Model.GetUserWebSiteResponse ret = new Model.GetUserWebSiteResponse();
            if (string.IsNullOrEmpty(req.UserName))
            {
                ret.Code = 1;
                ret.Message = "参数错误：UserName不能为空";
                return ret;
            }
            var list=new BLL.Authority().GetUserWebSite(req.UserName);
            if (list.Count > 0)
            {
                ret.WebSites = new List<Model.Data.WebSite>();
                foreach (var i in list)
                {
                    ret.WebSites.Add(new Model.Data.WebSite()
                    {
                        Code = i.Code,
                        Name = i.Name,
                        Address = i.Address,
                        IconCls = i.IconCls,
                        Sort = i.Sort
                    });
                }
            }
            ret.Code = 0;
            ret.Message = "成功获取数据";
            return ret;
        }

        /// <summary>
        /// 获取用户拥有权限的菜单
        /// </summary>
        public Model.GetUserMenuResponse GetUserMenu(string xml)
        {
            var req = Common.SerializationHelper.DeSerialize<Model.GetUserMenuRequest>(xml);
            Model.GetUserMenuResponse ret = new Model.GetUserMenuResponse();
            if (string.IsNullOrEmpty(req.UserName))
            {
                ret.Code = 1;
                ret.Message = "参数错误：UserName不能为空";
                return ret;
            }
            if (string.IsNullOrEmpty(req.WebSiteCode))
            {
                ret.Code = 1;
                ret.Message = "参数错误：WebSiteCode不能为空";
                return ret;
            }
            var menulist = new BLL.Authority().GetUserMenu(req.UserName, req.WebSiteCode, req.MenuCode);
            if (menulist.Count > 0)
            {
                ret.Menus = new List<Model.Data.Menu>();
                foreach (var i in menulist)
                {
                    ret.Menus.Add(new Model.Data.Menu()
                    {
                        Code = i.Code,
                        Name = i.Name,
                        ID = i.ID,
                        Address = i.Address,
                        IconCls = i.IconCls,
                        ParentCode = i.ParentCode,
                        Sort = i.Sort,
                        WebSiteCode = i.WebSiteCode
                    });
                }
            }
            ret.Code = 0;
            ret.Message = "成功获取数据";
            return ret;
        }
        #endregion
    }
}